﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Grpc.Net.Client;

namespace GrpcClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using (var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
            {
                //配置 https://docs.microsoft.com/zh-cn/aspnet/core/grpc/configuration
                MaxReceiveMessageSize = 5 * 1024 * 1024, // 5 MB
                MaxSendMessageSize = 2 * 1024 * 1024 // 2 MB
            }))
            {
                //未使用拦截器
                //var client = new Greeter.GreeterClient(channel);

                //注册拦截器，并使用 https://www.cnblogs.com/stulzq/p/11840535.html
                var invoker = channel.Intercept(new ClientLoggerInterceptor());
                var client = new Greeter.GreeterClient(invoker);

                try
                {
                    var reply = await client.SayHelloAsync(
                                      new HelloRequest { Name = "GreeterClient" }
                                      , deadline: DateTime.UtcNow.AddSeconds(5)// 设置超时时间
                                  );
                    Console.WriteLine("Greeting: " + reply.Message);

                    var req = await client.MathAddAsync(new AddRequest()
                    {
                        Num1 = 1,
                        Num2 = 2
                    });
                    Console.WriteLine("TotalNum: " + req.TotalNum);
                }
                catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded)
                {
                    Console.WriteLine("请求超时");
                }

            }

            Console.WriteLine("Press any key to exit...");

            Console.ReadKey();
        }
    }
}
